package com.bfsuol.yihang.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bfsuol.bfsuolframework.core.controller.SpringControllerSupport;
import com.bfsuol.bfsuolframework.core.controller.json.MessageJson;
import com.bfsuol.bfsuolframework.core.controller.support.Pagination;
import com.bfsuol.bfsuolframework.core.controller.support.QueryParam;
import com.bfsuol.bfsuolframework.core.spring.QueryParameter;
import com.bfsuol.bfsuolframework.core.utils.StringUtils;
import com.bfsuol.bfsuolframework.security.annotations.*;
import com.bfsuol.bfsuolframework.security.dao.RolePrivilege;
import com.bfsuol.common.Constants;
import com.bfsuol.yihang.cars.api.CommandVehicleService;
import com.bfsuol.yihang.cars.api.QueryVehicleService;
import com.bfsuol.yihang.cars.dto.VehicleDTO;
import com.bfsuol.yihang.customers.api.QueryCustomerService;
import com.bfsuol.yihang.customers.dto.CustomerDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/yihang/vehicle")
public class VehicleController extends SpringControllerSupport {

    @Autowired
    private QueryVehicleService queryVehicleService;
    @Autowired
    private CommandVehicleService commandVehicleService;
    @Autowired
    private QueryCustomerService queryCustomerService;

    @SecPrivilege(title = "车辆管理")
    @RequestMapping("/index")
    public ModelAndView index(@RequestParam(value = "id",required = false) Long id,Model model){
        if(id!=null){
            CustomerDTO customerDTO = queryCustomerService.getById(id);
            model.addAttribute("customer",customerDTO);
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(getViewNamedPath("index"));
        return modelAndView;
    }

    @SecList
    @RequestMapping("/list")
    public ModelAndView list(
            VehicleDTO vehicleDTO,
            @ModelAttribute("page") Pagination page){

        com.baomidou.mybatisplus.extension.plugins.pagination.Page page1 = new Page(page.getDefaultCurrentPage(),page.getPageSize());
        com.baomidou.mybatisplus.extension.plugins.pagination.Page vehiclePages = queryVehicleService.page(page1,vehicleDTO);
        page.setItems(vehiclePages.getRecords());
        page.setTotalRecord((int) vehiclePages.getTotal());

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(getViewNamedPath("list"));
        return modelAndView;
    }

    @RequestMapping("/input")
    public ModelAndView create(@ModelAttribute VehicleDTO vehicleDTO, Model model){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(getViewNamedPath("input"));
        return modelAndView;
    }

    @RequestMapping("/input/{id}")
    public ModelAndView edit(@PathVariable("id") Long id, Model model){
        VehicleDTO vehicleDTO = queryVehicleService.getById(id);
        model.addAttribute("vehicle",vehicleDTO);

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(getViewNamedPath("input"));
        return modelAndView;
    }

    @SecCreate
    @SecEdit
    @RequestMapping("/save")
    public @ResponseBody
    MessageJson save(@ModelAttribute VehicleDTO vehicleDTO){
        if(vehicleDTO.getVehicleType()==null)vehicleDTO.setVehicleType(Constants.GLOBAL_YESNO_NO);
        if(vehicleDTO.getVehicleIsTouBao()==null)vehicleDTO.setVehicleIsTouBao(Constants.GLOBAL_YESNO_NO);
        if(StringUtils.isBlank(vehicleDTO.getVehicleNo())) return MessageJson.fail("车牌号不能为空");
        VehicleDTO vehicleDTO1 = queryVehicleService.getOneByVehicleNo(vehicleDTO.getVehicleNo());
        if(vehicleDTO1 != null) return MessageJson.fail("车牌号已存在");

        if(vehicleDTO.getVehicleIsTouBao().equals(Constants.GLOBAL_YESNO_NO)){
            vehicleDTO.setTouBaoBeginTime(null);
            vehicleDTO.setTouBaoEndTime(null);
        }else if(vehicleDTO.getVehicleIsTouBao().equals(Constants.GLOBAL_YESNO_YES)){
            if(vehicleDTO.getTouBaoBeginTime() == null){
                return MessageJson.fail("必须设置保险开始时间");
            }
            if(vehicleDTO.getTouBaoEndTime() == null){
                return MessageJson.fail("必须设置保险结束时间");
            }
        }
        if(vehicleDTO.isNew()){
            vehicleDTO.setCreateTime(new Date());
            vehicleDTO.setUpdateTime(new Date());
            vehicleDTO.setCreateUserName(this.getLoginInfo().getLoginName());
            vehicleDTO.setUpdateUserName(this.getLoginInfo().getLoginName());
            commandVehicleService.save(vehicleDTO);
        }else{
            vehicleDTO.setUpdateTime(new Date());
            vehicleDTO.setUpdateUserName(this.getLoginInfo().getLoginName());
            commandVehicleService.updateById(vehicleDTO);
        }
        return MessageJson.information("保存成功");
    }

    @SecDelete
    @RequestMapping("/delete/{id}")
    public @ResponseBody
    MessageJson delete(@PathVariable("id") Long id) {
        if(id != null){
            commandVehicleService.deleteById(id);
        }
        return MessageJson.information("删除成功");
    }

    @RequestMapping("/dealWithCustomerView/input")
    public ModelAndView dealWithCustomerView(@RequestParam("ids") List<Long> ids, Model model){
        if(ids!=null&&ids.size()==1){
            VehicleDTO vehicleDTO = queryVehicleService.getById(ids.get(0));
            model.addAttribute("vehicle",vehicleDTO);
        }
        model.addAttribute("ids",ids.stream().map(String::valueOf).collect(Collectors.joining(",")));
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(getViewNamedPath("dealWithCustomer"));
        return modelAndView;
    }

    @SecEdit(title = "关联客户")
    @RequestMapping("/dealWithCustomer")
    public @ResponseBody MessageJson dealWithCustomer(@ModelAttribute VehicleDTO vehicleDTO){
        List<Long> ids = Arrays.stream(vehicleDTO.getIds().split(",")).map(Long::valueOf).collect(Collectors.toList());

        vehicleDTO.setUpdateTime(new Date());
        vehicleDTO.setUpdateUserName(this.getLoginInfo().getLoginName());
        if(vehicleDTO.getCustomerId()==null) return MessageJson.fail("客户id不能为空");
        if(StringUtils.isBlank(vehicleDTO.getCustomerName())) return MessageJson.fail("客户名称不能为空");
        CustomerDTO customerDTO = queryCustomerService.getById(vehicleDTO.getCustomerId());
        if(customerDTO == null) return MessageJson.fail("客户不存在");
        if(!vehicleDTO.getCustomerName().equals(customerDTO.getName())){
            return MessageJson.fail("客户名称不匹配");
        }
        ids.forEach(id->{
            VehicleDTO vehicleDTO1 = queryVehicleService.getById(id);
            vehicleDTO1.setCustomerId(vehicleDTO.getCustomerId());
            vehicleDTO1.setCustomerName(vehicleDTO.getCustomerName());
            vehicleDTO1.setUpdateTime(new Date());
            vehicleDTO1.setUpdateUserName(this.getLoginInfo().getLoginName());
            commandVehicleService.updateById(vehicleDTO1);
        });
        return MessageJson.information("保存成功");
    }
}
